package com.cneport.das.common.zip;


import com.cneport.das.common.utils.DateUtil;
import com.cneport.das.common.utils.FileUtil;
import com.cneport.das.common.utils.StringUtil;
import com.cneport.das.common.utils.ZipUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;

/**
 * @author GavinZhang
 * @version 1.0
 * @desc： 日志清理策略, 只清理业务日志，其它日志由日志框架处理。
 * @company 东方物通科技有限（北京）公司
 * @date 2021/8/26 11:51
 */
@Data
@Component
@Slf4j
public class BizLogClear {
    @Value("${logging.file.path}")
    private String basePath;
    @Value("${logging.clear.zip.keepLiveDays}")
    private int keepLiveDays;
    @Value("${logging.clear.zip.bizArchives.clearStrategy}")
    private int clearStrategy;

    @Scheduled(cron = "0 0 22 * * ?")
    public void clear() {
        long start = System.currentTimeMillis();
        log.info("开始执行压缩业务日志：-------------->");
        if (!StringUtil.isEmpty(basePath)) {
            File file = new File(basePath + File.separator + "biz");
            if (file.exists()) {
                Date now = new Date();
                Date pre = DateUtil.offsetDays(now, 0 - keepLiveDays);
                String dirName = DateUtil.format(pre, "yyyy-MM-dd");
                //遍历所有子目录
                String[] files = file.list();
                //由于改动，files这一层不再是日期，而是公司编号
                for (String fl : files) {
                    File tFile = new File(file + File.separator + fl);
                    File[] datedir = tFile.listFiles();
                    if (datedir != null && datedir.length > 0) {
                        for (File dfile : datedir) {
                            //这一层才是日期命名的
                            if (dfile.isDirectory()) {
                                String targetName = dfile.getName();
                                try {
                                    Date date = DateUtil.parse(targetName, "yyyy-MM-dd");
                                    if (date.getTime() < pre.getTime()) {
                                        ZipUtil.zip(dfile.getAbsolutePath(), dfile.getAbsolutePath() + ".zip", true);
                                        FileUtil.del(dfile.getAbsolutePath());
                                    }
                                } catch (Exception e) {
                                    log.error("文件目录分析出错：" + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
        long end = System.currentTimeMillis();
        log.info("<---------------压缩业务日志完成！耗时：" + (end - start) + "毫秒！");
    }

    /**
     * 删除过期的存档文件
     */
    @Scheduled(cron = "0 0 23 * * ?")
    public void checkArchives() {
        log.info("开始执行清理业务归档日志：-------------->");
        Date now = new Date();
        Date pre = null;
        if (clearStrategy == StrategyEnum.KEEP_3_YEAR.getValue()) {
            pre = DateUtil.offsetDays(now, -3 * 365);
        }
        if (clearStrategy == StrategyEnum.KEEP_1_YEAR.getValue()) {
            pre = DateUtil.offsetDays(now, -365);
        }
        if (clearStrategy == StrategyEnum.KEEP_3_MONTH.getValue()) {
            pre = DateUtil.offsetDays(now, -3 * 30);
        }
        if (clearStrategy == StrategyEnum.KEEP_30_DAYS.getValue()) {
            pre = DateUtil.offsetDays(now, -30);
        } else if (clearStrategy == StrategyEnum.KEEP_PERMANENT.getValue()) {
            pre = now;
        }
        if (pre != now) {
            if (!StringUtil.isEmpty(basePath)) {
                File file = new File(basePath + File.separator + "biz");
                String[] files = file.list();
                for (String filename : files) {
                    if (filename.endsWith(".zip")) {
                        String targetName = filename.substring(0, filename.indexOf(".zip"));
                        try {
                            Date date = DateUtil.parse(targetName, "yyyy-MM-dd");
                            if (date.getTime() < pre.getTime()) {
                                FileUtil.del(file.getAbsolutePath() + File.separator + filename);
                            }
                        } catch (Exception e) {
                            log.error("文件目录分析出错：" + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        log.info("<-----------------业务归档日志清理完成！");
    }

}
